package com.huikeportal.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.json.JSONArray;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.huikeportal.controller.common.Tools;
import com.huikeportal.dao.SelectSiteMapper;
import com.huikeportal.dao.UserSiteHistoryMapper;
import com.huikeportal.model.BrandModel;
import com.huikeportal.model.ChangeGcParam;
import com.huikeportal.model.DpModel;
import com.huikeportal.model.GcModel;
import com.huikeportal.model.MulSiteCondition;
import com.huikeportal.model.QyModel;
import com.huikeportal.model.RegionModel;
import com.huikeportal.model.SiteAllInfo;
import com.huikeportal.model.SiteCommon;
import com.huikeportal.model.SiteSimpleInfo;
import com.huikeportal.model.SquareChange;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.UserSiteHistory;
import com.huikeportal.model.common.SqlParameter;
import com.huikeportal.service.SelectSiteService;

@Service("selectSiteService")
public class SelectSiteServiceImpl implements SelectSiteService {

	@Autowired
	private SelectSiteMapper selectSiteMapper;

	@Autowired
	private UserSiteHistoryMapper userSiteHistoryMapper;

	/**
	 * 初始化显示全部有权限的广场
	 */
	public List<SiteAllInfo> getGcList(GcModel gcModel) throws Exception {
		List<SiteAllInfo> gcList = selectSiteMapper.queryGcList(gcModel);
		return gcList;
	}

	/**
	 * 查询地区列表
	 */
	public List<GcModel> queryDqList(GcModel gcModel) throws Exception {
		return selectSiteMapper.queryDqList(gcModel);
	}

	/**
	 * 查询商圈列表
	 */
	public List<GcModel> querySqList(GcModel gcModel) throws Exception {
		return selectSiteMapper.querySqList(gcModel);
	}

	/**
	 * 查询栏中查询广场
	 * 
	 * @param pageDataVo
	 * @param userInfo
	 * @return
	 * @throws Exception
	 */
	public List<SiteAllInfo> searchGc(GcModel gcModel) throws Exception {
		List<SiteAllInfo> gcList = selectSiteMapper.queryGcList(gcModel);
		return gcList;
	}

	/**
	 * 查询楼层
	 */
	public List<SiteAllInfo> queryLcList(SqlParameter sqlParameter)
			throws Exception {
		List<SiteAllInfo> lcList = selectSiteMapper.queryLcList(sqlParameter);
		return lcList;
	}

	/**
	 * 根据场所id查询场所信息
	 */
	public SiteCommon querySiteInfo(String siteId) throws Exception {
		return selectSiteMapper.querySiteInfo(siteId);
	}

	/**
	 * 根据广场查询所有楼层
	 */
	public List<SiteAllInfo> queryLcByGc(String string) throws Exception {
		return selectSiteMapper.queryLcByGc(string);
	}

	/**
	 * 查询区域
	 */
	public List<SiteAllInfo> queryQyList(QyModel qyModel) throws Exception {
		List<SiteAllInfo> qyList = selectSiteMapper.queryQyList(qyModel);
		return qyList;
	}

	/**
	 * 查询店铺数据
	 */
	public List<SiteAllInfo> queryDpList(DpModel dpModel) throws Exception {
		return selectSiteMapper.queryDpList(dpModel);
	}

	/**
	 * 查询店铺数据时初始化楼层信息
	 */
	public List<SiteAllInfo> selectLcByDp(String string) throws Exception {
		return selectSiteMapper.selectLcByDp(string);
	}

	/**
	 * 查询店铺数据时初始化品牌信息
	 */
	public List<SiteAllInfo> selectPpByDp(String string) throws Exception {
		List<SiteAllInfo> ppList = selectSiteMapper.selectPpByDp(string);
		// 为品牌加上首字母信息
		for (int i = 0; i < ppList.size(); i++) {
			String s = ppList.get(i).getSitename().substring(0, 1);
			char c = s.charAt(0);
			// 如果第一个字符是汉字
			Pattern pattern = Pattern
					.compile("^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]){1,1}$");
			Matcher matcher = pattern.matcher(s);
			if (matcher.find()) {
				String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(s
						.charAt(0));
				ppList.get(i).setArea(pinyin[0].substring(0, 1));
			}
			// 如果第一个字符是字母
			else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
				ppList.get(i).setArea(s.toLowerCase());
			}
			// 否则，设置为其他
			else {
				ppList.get(i).setArea("0");
			}
		}
		return ppList;
	}

	/**
	 * 保存选择结果
	 */
	public UserSiteHistory saveSelectResult(UserInfo userInfo, String siteId,
			String address) throws Exception {
		// 根据菜单跳转地址查询菜单信息
		SqlParameter sql = new SqlParameter();
		sql.setString(address);
		sql.setSysLang(userInfo.getSysLang());
		Integer menuId = selectSiteMapper.queryMenuIdByAddress(sql);
		// 查询要更新的表主键id
		UserSiteHistory userSiteHistory = new UserSiteHistory();
		userSiteHistory.setUserId(userInfo.getUserId());
		userSiteHistory.setMenuId(menuId);
		Integer historyId = selectSiteMapper.queryHistoryId(userSiteHistory);
		userSiteHistory.setId(historyId);
		userSiteHistory.setSiteId(siteId);
		userSiteHistory.setUpdateTime(new Date());
		// 更新表
		userSiteHistoryMapper.updateByPrimaryKeySelective(userSiteHistory);
		return userSiteHistory;
	}

	/**
	 * 多选场所初始化-所有的筛选条件
	 */
	public MulSiteCondition mulSelectLoad(MulSiteCondition mulSiteCondition)
			throws Exception {
		// 用户集团权限
		List<SiteAllInfo> userJtList = new ArrayList<SiteAllInfo>();
		// 用户广场权限
		List<SiteAllInfo> userGcList = new ArrayList<SiteAllInfo>();
		// 用户区域权限
		List<SiteAllInfo> userQyList = new ArrayList<SiteAllInfo>();
		// 用户楼层权限
		List<SiteAllInfo> userLcList = new ArrayList<SiteAllInfo>();
		// 用户店铺权限
		List<SiteAllInfo> userDpList = new ArrayList<SiteAllInfo>();
		// 用户根据店铺反查的广场权限
		List<SiteAllInfo> userDpGcList = new ArrayList<SiteAllInfo>();
		// 根据店铺反查的用户广场权限
		List<SiteAllInfo> userCgList = selectSiteMapper.selectGcByDp(Tools
				.pinjieId(mulSiteCondition.getDpList()));
		// 如果范围是多广场
		if ("0".equals(mulSiteCondition.getRangeType())) {
			userJtList = mulSiteCondition.getJtList();
			userGcList = mulSiteCondition.getGcList();
			userQyList = mulSiteCondition.getQyList();
			userLcList = mulSiteCondition.getLcList();
			userDpList = mulSiteCondition.getDpList();
			userDpGcList = userCgList;
		}
		// 如果范围是单广场
		else {
			userJtList = mulSiteCondition.getJtList();
			if (mulSiteCondition.getGcList().size() > 0) {
				userGcList.add(mulSiteCondition.getGcList().get(0));
			}
			QyModel qyModel = new QyModel();
			qyModel.setGcSiteId(Tools.pinjieId(userGcList));
			userQyList = selectSiteMapper.mulSelectQy(qyModel);
			SqlParameter sql = new SqlParameter();
			sql.setString(Tools.pinjieId(userGcList));
			userLcList = selectSiteMapper.mulSelectLc(sql);
			if (userCgList.size() > 0) {
				userDpGcList.add(userCgList.get(0));
			}
			DpModel dpModel = new DpModel();
			dpModel.setGcString(Tools.pinjieId(userDpGcList));
			dpModel.setDpString(Tools.pinjieId(mulSiteCondition.getDpList()));
			userDpList = selectSiteMapper.mulSelectDp(dpModel);
		}
		// 如果是通过更换广场页面返回
		if (mulSiteCondition.getQy_gcList() == null) {
			// 查询区域-广场范围
			mulSiteCondition.setQy_gcList(userGcList);
		}
		// 重新查询区域信息
		else {
			QyModel qyModel = new QyModel();
			qyModel
					.setGcSiteId(Tools
							.pinjieId(mulSiteCondition.getQy_gcList()));
			userQyList = selectSiteMapper.mulSelectQy(qyModel);
		}
		// 查询区域-楼层
		mulSiteCondition.setQy_lcList(getCommonLc(mulSiteCondition
				.getQy_gcList()));
		if (mulSiteCondition.getLc_gcList() == null) {
			// 查询楼层-广场范围
			mulSiteCondition.setLc_gcList(userGcList);
		} else {
			SqlParameter sql = new SqlParameter();
			sql.setString(Tools.pinjieId(mulSiteCondition.getLc_gcList()));
			userLcList = selectSiteMapper.mulSelectLc(sql);
		}
		// 查询楼层-楼层
		mulSiteCondition.setLc_lcList(getCommonLc(mulSiteCondition
				.getLc_gcList()));
		if (mulSiteCondition.getDp_gcList() == null) {
			// 查询店铺-广场范围
			mulSiteCondition.setDp_gcList(userDpGcList);
		} else {
			DpModel dpModel = new DpModel();
			dpModel
					.setGcString(Tools
							.pinjieId(mulSiteCondition.getDp_gcList()));
			dpModel.setDpString(Tools.pinjieId(mulSiteCondition.getDpList()));
			userDpList = selectSiteMapper.mulSelectDp(dpModel);
		}
		// 查询店铺-品牌
		List<SiteAllInfo> ppList = selectSiteMapper.selectPpByDp(Tools
				.pinjieId(userDpList));
		mulSiteCondition.setDp_ppList(ppList);
		// 查询店铺-楼层
		mulSiteCondition.setDp_lcList(getCommonLc(mulSiteCondition
				.getDp_gcList()));
		// 查询广场-地域
		GcModel gcModel = new GcModel();
		gcModel.setGuangchangString(Tools
				.pinjieId(mulSiteCondition.getGcList()));
		mulSiteCondition.setGc_dqList(selectSiteMapper.queryDqList(gcModel));
		// 查询广场-国家
		mulSiteCondition.setGc_guoList(getGuojiaList());
		// 查询广场-商圈
		mulSiteCondition.setGc_sqList(selectSiteMapper.querySqList(gcModel));
		// 为品牌加上首字母信息
		for (int i = 0; i < ppList.size(); i++) {
			String s = ppList.get(i).getSitename().substring(0, 1);
			char c = s.charAt(0);
			// 如果第一个字符是汉字
			Pattern pattern = Pattern
					.compile("^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]){1,1}$");
			Matcher matcher = pattern.matcher(s);
			if (matcher.find()) {
				String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(s
						.charAt(0));
				ppList.get(i).setArea(pinyin[0].substring(0, 1));
			}
			// 如果第一个字符是字母
			else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
				ppList.get(i).setArea(s.toLowerCase());
			}
			// 否则，设置为其他
			else {
				ppList.get(i).setArea("0");
			}
		}
		// 拼接区域查询结果
		if ("0".equals(mulSiteCondition.getRangeType())) {
			mulSiteCondition.setQyList(selectSiteMapper.pinjieGc(Tools
					.pinjieId(userQyList)));
			// 拼接楼层查询结果
			mulSiteCondition.setLcList(selectSiteMapper.pinjieGc(Tools
					.pinjieId(userLcList)));
			// 拼接店铺查询结果
			mulSiteCondition.setDpList(selectSiteMapper.pinjieGc(Tools
					.pinjieId(userDpList)));
		} else {
			mulSiteCondition.setQyList(userQyList);
			// 拼接楼层查询结果
			mulSiteCondition.setLcList(userLcList);
			// 拼接店铺查询结果
			mulSiteCondition.setDpList(userDpList);
		}
		return mulSiteCondition;
	}

	/**
	 * 查询广场共同楼层
	 * 
	 * @param gcList
	 * @return
	 * @throws Exception
	 */
	private List<SiteAllInfo> getCommonLc(List<SiteAllInfo> gcList)
			throws Exception {
		boolean flag = true;
		List<SiteAllInfo> lcList = new ArrayList<SiteAllInfo>();
		// 定义结果集
		List<SiteAllInfo> resultList = new ArrayList<SiteAllInfo>();
		// 辅助map
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		// 循环所有的广场，查询旗下的楼层信息
		for (int i = 0; i < gcList.size(); i++) {
			List<SiteAllInfo> lc = selectSiteMapper.queryLcByGc(gcList.get(i)
					.getSiteid());
			List<String> lcNameList = new ArrayList<String>();
			if (lc.size() > 0) {
				for (int j = 0; j < lc.size(); j++) {
					lcNameList.add(lc.get(j).getSitename());
				}
				map.put(gcList.get(i).getSiteid(), lcNameList);
				lcList.addAll(lc);
			}
		}
		// 循环所有的楼层信息，如果存在每个广场都包含，加入结果集
		for (int i = 0; i < lcList.size(); i++) {
			flag = true;
			for (int j = 0; j < gcList.size(); j++) {
				List<String> lcNameList = map.get(gcList.get(j).getSiteid());
				// 如果存在有广场下的楼层无此楼层名称，则不加入结果集
				if (!lcNameList.contains(lcList.get(i).getSitename())) {
					flag = false;
					break;
				}
			}
			if (flag) {
				resultList.add(lcList.get(i));
			}
		}
		return resultList;
	}

	/**
	 * 下拉框联动
	 */
	public List<SiteAllInfo> searchCombo(String type, String id)
			throws Exception {
		// 选择国家
		if ("0".equals(type)) {
			return selectSiteMapper.selectShengCombo(Integer.parseInt(id));
		}
		// 选择省
		else if ("1".equals(type)) {
			return selectSiteMapper.selectShiCombo(Integer.parseInt(id));
		}
		// 选择市
		else if ("2".equals(type)) {
			return selectSiteMapper.selectQuCombo(Integer.parseInt(id));
		}
		return null;
	}

	/**
	 * 多选查询店铺
	 */
	public List<SiteAllInfo> mulSelectDp(DpModel dpModel) throws Exception {
		return selectSiteMapper.pinjieGc(Tools.pinjieId(selectSiteMapper
				.mulSelectDp(dpModel)));
	}

	/**
	 * 多选查询楼层
	 */
	public List<SiteAllInfo> mulSelectLc(SqlParameter sqlParameter)
			throws Exception {
		return selectSiteMapper.pinjieGc(Tools.pinjieId(selectSiteMapper
				.mulSelectLc(sqlParameter)));
	}

	/**
	 * 多选查询区域
	 */
	public List<SiteAllInfo> mulSelectQy(QyModel qyModel) throws Exception {
		// TODO Auto-generated method stub
		return selectSiteMapper.pinjieGc(Tools.pinjieId(selectSiteMapper
				.mulSelectQy(qyModel)));
	}

	/**
	 * 品牌选择初始化
	 */
	public MulSiteCondition brandSelectLoad(MulSiteCondition mulSiteCondition)
			throws Exception {
		// 查询店铺-广场范围
		mulSiteCondition.setDp_gcList(mulSiteCondition.getGcList());
		// 根据广场查询店铺
		DpModel dpModel = new DpModel();
		dpModel.setDpString(Tools.pinjieId(mulSiteCondition.getDpList()));
		dpModel.setGcString(Tools.pinjieId(mulSiteCondition.getGcList()));
		List<SiteAllInfo> dpList = selectSiteMapper.mulSelectDp(dpModel);
		// 根据店铺查询品牌信息
		List<SiteAllInfo> ppList = selectSiteMapper.selectPpByDp(Tools
				.pinjieId(dpList));
		// 为品牌加上首字母信息
		for (int i = 0; i < ppList.size(); i++) {
			String s = ppList.get(i).getSitename().substring(0, 1);
			char c = s.charAt(0);
			// 如果第一个字符是汉字
			Pattern pattern = Pattern
					.compile("^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]){1,1}$");
			Matcher matcher = pattern.matcher(s);
			if (matcher.find()) {
				String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(s
						.charAt(0));
				ppList.get(i).setArea(pinyin[0].substring(0, 1));
			}
			// 如果第一个字符是字母
			else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
				ppList.get(i).setArea(s.toLowerCase());
			}
			// 否则，设置为其他
			else {
				ppList.get(i).setArea("0");
			}
		}
		mulSiteCondition.setDp_ppList(ppList);
		return mulSiteCondition;
	}

	/**
	 * 获取国家下拉框数据
	 */
	public String getGuojiaList() throws Exception {
		JSONArray guojiaArray = JSONArray.fromObject(selectSiteMapper
				.selectGuojiaCombo());
		return guojiaArray.toString();
	}

	/**
	 * 更换广场初始化
	 */
	public SquareChange squareChangeLoad(ChangeGcParam changeGcParam,
			List<SiteAllInfo> dpGcList, List<SiteAllInfo> yuanGcList)
			throws Exception {
		SquareChange squareChange = new SquareChange();
		GcModel gcModel = new GcModel();
		// // 如果是获取用户自己的广场权限
		// if ("0".equals(changeGcParam.getGcDataType())) {
		// gcModel.setGuangchangString(Tools.pinjieId(gcList));
		// }
		// // 如果是根据店铺反查
		// else if ("1".equals(changeGcParam.getGcDataType())) {
		// List<SiteAllInfo> guangchang = selectSiteMapper.selectGcByDp(Tools
		// .pinjieId(dpList));
		// gcModel.setGuangchangString(Tools.pinjieId(guangchang));
		// }
		gcModel.setGuangchangString(Tools.pinjieId(dpGcList));
		// 查询地区
		squareChange.setDqList(selectSiteMapper.queryDqList(gcModel));
		// 查询商圈
		// squareChange.setSqList(selectSiteMapper.querySqList(gcModel));
		// 查询广场初始化数据
		List<SiteAllInfo> gcList = selectSiteMapper.queryGcList(gcModel);
		// 给广场加上是否是自身权限标签，0：不是自己权限范围内的；1：是自己权限范围内的
		for (int i = 0; i < gcList.size(); i++) {
			if (Tools.isHaveGcPer(yuanGcList, gcList.get(i).getSiteid())) {
				gcList.get(i).setSitestaus(1);
			} else {
				gcList.get(i).setSitestaus(0);
			}
		}
		squareChange.setGcList(gcList);
		// 查询国家下拉框列表
		squareChange.setGuojia(getGuojiaList());
		return squareChange;
	}

	public Integer getMenuId(SqlParameter sql) throws Exception {
		return selectSiteMapper.queryMenuIdByAddress(sql);
	}

	// 获取集团&地区列表
	public List<SiteAllInfo> getJtDqList(SqlParameter sql) throws Exception {
		return selectSiteMapper.getJtDqList(sql);
	}

	// 获取场所基本信息
	public List<SiteSimpleInfo> getSimpleSiteList(String string)
			throws Exception {
		return selectSiteMapper.getSimpleSiteList(string);
	}

	// 获取店铺信息
	public List<SiteAllInfo> getTwiceDp(RegionModel regionModel)
			throws Exception {
		return selectSiteMapper.getTwiceDp(regionModel);
	}

	// 获取楼层信息
	public List<SiteAllInfo> getTwiceLc(RegionModel regionModel)
			throws Exception {
		return selectSiteMapper.getTwiceLc(regionModel);
	}

	// 获取区域信息
	public List<SiteAllInfo> getTwiceQy(RegionModel regionModel)
			throws Exception {
		return selectSiteMapper.getTwiceQy(regionModel);
	}

	// 获取品牌信息
	public List<BrandModel> getBrandList(BrandModel brandModel)
			throws Exception {
		List<BrandModel> brandList = selectSiteMapper
				.queryBrandByGc(brandModel);
		// 拼接品牌首字母
		for (int i = 0; i < brandList.size(); i++) {
			String s = brandList.get(i).getBrandName().substring(0, 1);
			char c = s.charAt(0);
			// 如果第一个字符是汉字
			Pattern pattern = Pattern
					.compile("^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]){1,1}$");
			Matcher matcher = pattern.matcher(s);
			if (matcher.find()) {
				String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(s
						.charAt(0));
				brandList.get(i).setBrandZiMu(pinyin[0].substring(0, 1));
			}
			// 如果第一个字符是字母
			else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
				brandList.get(i).setBrandZiMu(s.toLowerCase());
			}
			// 否则，设置为其他
			else {
				brandList.get(i).setBrandZiMu("0");
			}
		}
		return brandList;
	}
}
